package com.yangyang.notepad;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ExcelHelper {
    private final Context context;
    private final NoteDatabaseHelper databaseHelper;

    public ExcelHelper(Context context, NoteDatabaseHelper databaseHelper) {
        this.context = context;
        this.databaseHelper = databaseHelper;
    }

    public void exportNotes() {
        List<Note> notes = databaseHelper.getAllNotes();

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Notes");

            // 创建标题行
            createHeaderRow(sheet);

            // 填充数据
            fillDataRows(sheet, notes);

            // 保存文件
            File exportFile = createExportFile();
            saveWorkbook(workbook, exportFile);

            // 通知用户
            showExportSuccess(exportFile);

        } catch (Exception e) {
            showError("导出失败", e);
        }
    }

    private void createHeaderRow(Sheet sheet) {
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("Title");
        headerRow.createCell(2).setCellValue("Content");
        headerRow.createCell(3).setCellValue("Create Time");
        headerRow.createCell(4).setCellValue("Update Time");
    }

    private void fillDataRows(Sheet sheet, List<Note> notes) {
        for (int i = 0; i < notes.size(); i++) {
            Note note = notes.get(i);
            Row row = sheet.createRow(i + 1);

            row.createCell(0).setCellValue(note.getId());
            row.createCell(1).setCellValue(note.getTitle());
            row.createCell(2).setCellValue(note.getContent());
            row.createCell(3).setCellValue(DateUtil.longFormatTime(note.getCreateTime()));
            row.createCell(4).setCellValue(DateUtil.longFormatTime(note.getUpdateTime()));
        }
    }


    private File createExportFile() {
        File exportDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "Notepad Exports");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }

        String fileName = "notes_export_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()) + ".xlsx";
        return new File(exportDir, fileName);
    }

    private void saveWorkbook(Workbook workbook, File exportFile) throws Exception {
        try (FileOutputStream outputStream = new FileOutputStream(exportFile)) {
            workbook.write(outputStream);
        }
    }

    private void showExportSuccess(File exportFile) {
        Toast.makeText(context, "导出成功: " + exportFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
    }

    public void importNotes(Uri uri) {
        try (InputStream inputStream = context.getContentResolver().openInputStream(uri); Workbook workbook = new XSSFWorkbook(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0);
            ImportResult result = processImportSheet(sheet);

            // 刷新数据
            if (result.getImportedCount() > 0) {
                notifyDataChanged();
            }

            // 显示结果
            showImportResult(result);

        } catch (Exception e) {
            showError("导入失败", e);
        }
    }

    private ImportResult processImportSheet(Sheet sheet) {
        ImportResult result = new ImportResult();

        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            try {
                Note note = createNoteFromRow(row);
                databaseHelper.addNote(note);
                result.incrementImported();
            } catch (Exception e) {
                result.incrementSkipped();
            }
        }

        return result;
    }

    private Note createNoteFromRow(Row row) throws Exception {
        Note note = new Note(getCellStringValue(row.getCell(1)), // title
                getCellStringValue(row.getCell(2))  // content
        );

        // 设置时间戳
        String createdAtStr = getCellStringValue(row.getCell(3));
        String updatedAtStr = getCellStringValue(row.getCell(4));

        if (!createdAtStr.isEmpty()) {
            note.setCreateTime(DateUtil.timeStrToLong(createdAtStr));
        }

        if (!updatedAtStr.isEmpty()) {
            note.setUpdateTime(DateUtil.timeStrToLong(updatedAtStr));
        }

        return note;
    }

    private String getCellStringValue(Cell cell) {
        if (cell == null) return "";
        DataFormatter formatter = new DataFormatter();
        return formatter.formatCellValue(cell);
    }

    private void notifyDataChanged() {
        // 可以通过接口回调或事件总线通知Fragment刷新数据
        if (context instanceof DataChangeListener) {
            ((DataChangeListener) context).onDataChanged();
        }
    }

    private void showImportResult(ImportResult result) {
        Toast.makeText(context, String.format("导入完成: %d条成功, %d条跳过", result.getImportedCount(), result.getSkippedCount()), Toast.LENGTH_LONG).show();
    }

    private void showError(String message, Exception e) {
        e.printStackTrace();
        Toast.makeText(context, message + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
    }

    // 导入结果封装类
    private static class ImportResult {
        private int importedCount = 0;
        private int skippedCount = 0;

        public int getImportedCount() {
            return importedCount;
        }

        public int getSkippedCount() {
            return skippedCount;
        }

        public void incrementImported() {
            importedCount++;
        }

        public void incrementSkipped() {
            skippedCount++;
        }
    }

    // 数据变化监听接口
    public interface DataChangeListener {
        void onDataChanged();
    }
}